package com.topscomm.gpm.script;

import com.topscomm.basic.BasicEntity;
import com.topscomm.cbo.pojo.CboApprovalNodeInsEntity;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.gpm.GpmScript;
import com.topscomm.gpm.GpmSystemConst;
import com.topscomm.gpm.pojo.GpmProjectAppointmentEntity;
import com.topscomm.gpm.pojo.GpmProjectEntity;
import com.topscomm.gpm.pojo.GpmProjectStakeholderEntity;
import com.topscomm.gpm.pojo.GpmProjectTeamEntity;
import com.topscomm.gpm.service.impl.GpmProjectAppointmentService;
import com.topscomm.gpm.service.impl.GpmProjectService;
import com.topscomm.gpm.service.impl.GpmProjectStakeholderService;
import com.topscomm.gpm.service.impl.GpmProjectTeamService;
import com.topscomm.tap.ITapService;
import com.topscomm.tap.TapEntity;
import com.topscomm.tap.common.ParameterCache;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description TODO
 * @Classname SdProjectTeamScript
 * @Date 2021/12/16
 * @Created by jiangtao
 */
public class GpmProjectTeamScript extends GpmScript {
	/**
	 * 任命审批结束后更新任命书和项目组成员信息和项目立项主表信息
	 * 同时将项目状态改为：策划阶段
	 * @param service
	 * @param entity
	 * @throws Exception
	 * @modify: liuchenguang 2021-8-11 增加相关方添加、更新、删除
	 */
	@Transactional
	public void projectTeamAfterApproval(ITapService service, TapEntity entity) throws Exception {
		// 审批节点实例
		CboApprovalNodeInsEntity nodeins = (CboApprovalNodeInsEntity) entity;
		String sourceid = ConvertUtil.convertToString(nodeins.getSourceid());
		GpmProjectAppointmentService gpmProjectAppointmentService = (GpmProjectAppointmentService) SpringUtil
				.getBean("gpmProjectAppointmentService");
		GpmProjectTeamService gpmProjectTeamService = (GpmProjectTeamService) SpringUtil
				.getBean("gpmProjectTeamService");
		GpmProjectService gpmProjectService = (GpmProjectService) SpringUtil
				.getBean("gpmProjectService");
		GpmProjectStakeholderService gpmProjectStakeholderService = (GpmProjectStakeholderService) SpringUtil
				.getBean("gpmProjectStakeholderService");
		//更新任命书签发日期
		GpmProjectAppointmentEntity gpmProjectAppointmentEntity = gpmProjectAppointmentService.queryById(sourceid);
		gpmProjectAppointmentEntity.setSigndate(new Date());
		gpmProjectAppointmentService.updateEntity(gpmProjectAppointmentEntity);
		// 获取项目编号，任命书id
		String projectCode = gpmProjectAppointmentEntity.getProjectcode();
		String appointmentId = ConvertUtil.convertToString(gpmProjectAppointmentEntity.getId());
		//查询项目entity
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendLineSingle("projectcode = '{0}'", projectCode);
		List<GpmProjectEntity> sdProjectEntities = gpmProjectService.queryByWhere(sql.toString());
		String sysPush = gpmProjectAppointmentEntity.getSyspush();
		// 首次任命时更新状态
		if(!CollectionUtils.isEmpty(sdProjectEntities) && !StringUtil.isEmpty(sysPush) && sysPush.equals("1")){
			GpmProjectEntity gpmProjectEntity = sdProjectEntities.get(0);
			//更新状态：策划状态（任命审批结束到策划审批结束）
			gpmProjectEntity.setProjectstate(GpmSystemConst.SdProjectState.ProjectPlaning);
			gpmProjectService.updateEntity(gpmProjectEntity);
		}
		// 任命审批通过后给项目组表添加项目领导组成员
		if (GpmSystemConst.Sd_APPOINTMENT_SYSPUSH.equals(gpmProjectAppointmentEntity.getSyspush())) {
			long appointmentEntityId = gpmProjectAppointmentEntity.getId();
			insertTeam(appointmentEntityId, gpmProjectAppointmentEntity.getProjectmanagercode(), gpmProjectAppointmentEntity.getProjectmanager(),
					"项目领导组", GpmSystemConst.WorkGroupRoleCode.pm, projectCode, 0L);
			// 如果sponsor为空，则不向相关方中添加sponsor
			if (!StringUtil.isEmpty(gpmProjectAppointmentEntity.getSponsorcode())) {
				insertTeam(appointmentEntityId, gpmProjectAppointmentEntity.getSponsorcode(), gpmProjectAppointmentEntity.getSponsor(),
						"项目领导组", GpmSystemConst.WorkGroupRoleCode.sponsor, projectCode, 0L);
			}
			insertTeam(appointmentEntityId, gpmProjectAppointmentEntity.getOwnercode(), gpmProjectAppointmentEntity.getOwner(),
					"项目领导组", GpmSystemConst.WorkGroupRoleCode.owner, projectCode, 0L);
			String adviserCode = gpmProjectAppointmentEntity.getAdvisercode();
			String adviser = gpmProjectAppointmentEntity.getAdviser();
			if (!StringUtil.isEmpty(adviser) && !StringUtil.isEmpty(adviserCode)) {
				insertTeam(appointmentEntityId, adviserCode, adviser, "项目领导组",
						"顾问", projectCode, 0L);
			}
		}

		// 获取项目组成员列表
		if (!StringUtil.isEmpty(appointmentId)) {
			StringBufferProxy whereSql = new StringBufferProxy();
			whereSql.appendLineSingle("appointmentid = '{0}'", appointmentId);
			List<GpmProjectTeamEntity> sdProjectTeamEntities = gpmProjectTeamService.queryByWhere(whereSql.toString());
			//如果包含项目经理,Sponsor,Owner变更，则回写主表
			boolean isChangePmSpnsorOwner = false;
			// 根据任命or撤销，任命:回写字段，撤销:查询原有成员进行撤销操作并回写字段
			List<BasicEntity> stakeHolderEntities = new ArrayList<BasicEntity>();
			List<BasicEntity> teamEntities = new ArrayList<BasicEntity>();
			List<BasicEntity> projectEntities = new ArrayList<BasicEntity>();
			for (GpmProjectTeamEntity gpmProjectTeamEntity : sdProjectTeamEntities) {
				// 9已审核，项目组成员状态和主表state保持一致
				gpmProjectTeamEntity.setState(9);
				String appointmentType = gpmProjectTeamEntity.getAppointmenttype();
				// 1任命，2撤销
				if ("1".equals(appointmentType)) {
					gpmProjectTeamEntity.setAppointdate(new Date());
					teamEntities.add(gpmProjectTeamEntity);
					// 添加相关方人员
					String roleCode = gpmProjectTeamEntity.getProjectrole();
					if(gpmProjectStakeholderService.isCenter(roleCode)) {
						// 添加项目组成员
						GpmProjectStakeholderEntity stakeholderEntity = gpmProjectStakeholderService
								.addStakeholderInfo(gpmProjectTeamEntity);
						if (stakeholderEntity != null) {
							stakeHolderEntities.add(stakeholderEntity);
						}
					}
				} else if ("2".equals(appointmentType)) {
					gpmProjectTeamEntity.setRevokedate(new Date());
					teamEntities.add(gpmProjectTeamEntity);
					String revokeUsercode = gpmProjectTeamEntity.getUsercode();
					String projectCodeFromTeam = gpmProjectTeamEntity.getProjectcode();
					String projectRole = gpmProjectTeamEntity.getProjectrole();
					String workGroup = gpmProjectTeamEntity.getWorkgroup();
					whereSql.clear();
					whereSql.appendSingle(
							"usercode = '{0}' and projectcode = '{1}' and projectrole = '{2}' "
									+ "and workgroup = '{3}' and appointmenttype = '1' and enabled = 1 ",
							revokeUsercode, projectCodeFromTeam, projectRole, workGroup);
					List<GpmProjectTeamEntity> sdProjectTeamEntities2 = gpmProjectTeamService
							.queryByWhere(whereSql.toString());
					if (!sdProjectTeamEntities2.isEmpty()) {
						GpmProjectTeamEntity gpmProjectTeamEntity2 = sdProjectTeamEntities2.get(0);
						gpmProjectTeamEntity2.setEnabled(0);
						gpmProjectTeamService.updateEntity(gpmProjectTeamEntity2);
						// 撤销相关方人员
						String roleCode = gpmProjectTeamEntity.getProjectrole();
						if(gpmProjectStakeholderService.isCenter(roleCode)) {
							// 撤销相关方表中人员，领导组人员不撤销
							gpmProjectStakeholderService.revokeStakeholderInfo(sdProjectTeamEntities2.get(0));
						}
					}
				}
				// 判断项目主表是否经过变更
				if("pm".equals(gpmProjectTeamEntity.getProjectrole()) && "1".equals(appointmentType)) {
					if(!sdProjectEntities.isEmpty()) {
						GpmProjectEntity gpmProjectEntity =sdProjectEntities.get(0);
						gpmProjectEntity.setProjectmanagercode(gpmProjectTeamEntity.getUsercode());
						gpmProjectEntity.setProjectmanager(gpmProjectTeamEntity.getUsername());
						projectEntities.add(gpmProjectEntity);
						isChangePmSpnsorOwner =true;
					}
				}
				if("sponsor".equals(gpmProjectTeamEntity.getProjectrole()) && "1".equals(appointmentType)) {
					if(!sdProjectEntities.isEmpty()) {
						GpmProjectEntity gpmProjectEntity =sdProjectEntities.get(0);
						gpmProjectEntity.setSponsorcode(gpmProjectTeamEntity.getUsercode());
						gpmProjectEntity.setSponsor(gpmProjectTeamEntity.getUsername());
						projectEntities.add(gpmProjectEntity);
						isChangePmSpnsorOwner =true;
					}
				}
				if("owner".equals(gpmProjectTeamEntity.getProjectrole()) && "1".equals(appointmentType)) {
					if(!sdProjectEntities.isEmpty()) {
						GpmProjectEntity gpmProjectEntity =sdProjectEntities.get(0);
						gpmProjectEntity.setOwnercode(gpmProjectTeamEntity.getUsercode());
						gpmProjectEntity.setOwner(gpmProjectTeamEntity.getUsername());
						projectEntities.add(gpmProjectEntity);
						isChangePmSpnsorOwner =true;
					}
				}
			}
			// 批量插入相关方表，批量更新项目组成员表、项目表
			if (!stakeHolderEntities.isEmpty()) {
				gpmProjectStakeholderService.insertBatch(stakeHolderEntities);
			}
			gpmProjectTeamService.updateBatch(teamEntities);
			if (!projectEntities.isEmpty()) {
				gpmProjectService.updateBatch(projectEntities);
			}
		}
	}
	/**
	 * @param
	 * @param appointmentid
	 * @param usercode
	 * @param username
	 * @param workgroup
	 * @param projectrole
	 * @return
	 * @Title: insertTeam
	 * @description:插入项目组成员
	 * @author: lanjianwei
	 * @date: 2021年1月16日下午5:32:57
	 * @modify:
	 */
	private void insertTeam(long appointmentid, String usercode, String username, String workgroup, String projectrole,
			String projectcode, Long teamId) {
		GpmProjectTeamService gpmProjectTeamService = (GpmProjectTeamService) SpringUtil
				.getBean("gpmProjectTeamService");
		GpmProjectTeamEntity gpmProjectTeamEntity = new GpmProjectTeamEntity();
		gpmProjectTeamEntity.setProjectcode(projectcode);
		gpmProjectTeamEntity.setProjectrole(projectrole);
		gpmProjectTeamEntity.setWorkgroup(workgroup);
		gpmProjectTeamEntity.setUsercode(usercode);
		gpmProjectTeamEntity.setUsername(username);
		gpmProjectTeamEntity.setAppointmenttype("1");
		gpmProjectTeamEntity.setAppointmentid(appointmentid);
		gpmProjectTeamEntity.setAppointdate(new Date());
		gpmProjectTeamEntity.setState(1);
		gpmProjectTeamEntity.setTeamid(teamId);
		String sd_leaderDuty = ParameterCache.getValue("Gpm_LeaderDuty");
		String[] split = sd_leaderDuty.split("。");
		if ("pm".equals(projectrole)) {
			gpmProjectTeamEntity.setDuty(split[2]);
		} else if ("sponsor".equals(projectrole)) {
			gpmProjectTeamEntity.setDuty(split[0]);
		} else {
			gpmProjectTeamEntity.setDuty(split[1]);
		}
		gpmProjectTeamService.insert(gpmProjectTeamEntity);
	}
}
